package org.siteanalyser.service.impl;

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.siteanalyser.domain.Message;
import org.siteanalyser.service.Service;
import org.siteanalyser.service.SystemException;
import org.springframework.beans.factory.annotation.Required;

public class FileCheckServiceImpl implements Service {
	
	private String fileNameToCheck;

    public void process(final Message message) throws SystemException {
        makeRequest(message);
    }

    private void makeRequest(final Message message) {
        final String url = message.getRequest().getUrl();
        Document doc = null;
        try {
            doc = Jsoup.connect(url+"/"+fileNameToCheck).get();
        } catch (final IOException e) {
        	// file does not exist
            //throw new SystemException(e.getMessage());
            message.getReport().addReportItem(fileNameToCheck, false);
            return;
        }
        if (doc == null) {
            throw new SystemException(String.format("Unable to parse URL: %s", url+"/"+fileNameToCheck));
        } 
    	// file exists
        message.getReport().addReportItem(fileNameToCheck, true);
    }

	public String getFileNameToCheck() {
		return fileNameToCheck;
	}

    @Required
	public void setFileNameToCheck(String fileNameToCheck) {
		this.fileNameToCheck = fileNameToCheck;
	}
}
